package leetcode_字符串._09高精度运算;

/**
 * 字符串相加
 * 算法 :
 * 将两个字符串反转
 * 对应位相加
 * 再设置一个进位
 */
public class _415 {

    public String addStrings(String num1, String num2) {
        num1 = new StringBuffer(num1).reverse().toString();
        num2 = new StringBuffer(num2).reverse().toString();
        StringBuilder ans = new StringBuilder();
        String max = num1.length() >= num2.length() ? num1 : num2;
        int len = Math.min(num1.length(), num2.length());
        int carry = 0;
        for (int i = 0; i < len; i++) {
            int tem = Integer.parseInt(num1.charAt(i) + "") + Integer.parseInt(num2.charAt(i) + "") + carry;
            ans.append(tem % 10);
            carry = tem / 10;
        }
        for (int i = len; i < max.length(); i++) {
            int tem = Integer.parseInt(max.charAt(i) + "") + carry;
            ans.append(tem % 10);
            carry = tem / 10;
        }
        if (carry == 1) {
            ans.append(1);
        }
        return ans.reverse().toString();
    }

    public String addStrings_perfect(String num1, String num2) {
        int i = num1.length() - 1, j = num2.length() - 1, add = 0;
        StringBuilder ans = new StringBuilder();
        // add != 0 是这种情况 9 + 1
        while (i >= 0 || j >= 0 || add != 0) {
            int x = i >= 0 ? num1.charAt(i) - '0' : 0;
            int y = j >= 0 ? num2.charAt(j) - '0' : 0;
            int res = x + y + add;
            ans.append(res % 10);
            add = res / 10;
            i--;
            j--;
        }
        return ans.reverse().toString();
    }
}
